package edu.ynu.se.xiecheng.achitectureclass.controller;

import edu.ynu.se.xiecheng.achitectureclass.common.dto.TokenResponseDTO;
import edu.ynu.se.xiecheng.achitectureclass.dto.SensorDataDTO;
import edu.ynu.se.xiecheng.achitectureclass.service.FboxService;
import edu.ynu.se.xiecheng.achitectureclass.dao.SensorDataDao;
import edu.ynu.se.xiecheng.achitectureclass.entity.SensorData;
import edu.ynu.se.xiecheng.achitectureclass.entity.Device;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Arrays;
import java.util.Map;
import java.util.Date;
import java.util.stream.Collectors;

@Api(tags = "Fbox接口")
@RestController
@RequestMapping("/api/fbox")
@CrossOrigin
public class FboxController {
    private static final Logger logger = LoggerFactory.getLogger(FboxController.class);

    @Autowired
    private FboxService fboxService;

    @Autowired
    private SensorDataDao sensorDataDao;

    @ApiOperation("获取Token")
    @PostMapping("/token")
    public TokenResponseDTO getToken() {
        logger.info("Getting token");
        return fboxService.getToken();
    }

    @ApiOperation("获取传感器数据")
    @PostMapping("/sensor/data")
    public List<SensorDataDTO> getSensorData(
        @RequestParam String boxNo,
        @RequestBody(required = false) Map<String, List<String>> request) {
        
        try {
            // 如果没有传入ids，使用默认的传感器列表
            List<String> sensorIds = (request != null && request.get("ids") != null) 
                ? request.get("ids")
                : Arrays.asList(
                    "327061375295689615", // 土壤含水率
                    "327061375295689614", // 土壤温度
                    "327061375295689605", // 土壤电导率
                    "327061375295689606", // 土壤PH
                    "327061375295689607", // 土壤氮含量
                    "327061375295689608", // 土壤磷含量
                    "327061375295689609", // 土壤钾含量
                    "327061375295689611", // 空气温度
                    "327061375295689612", // 空气湿度
                    "327061375295689613", // 光照度
                    "327061375295689610"  // CO2
                );
                
            logger.info("Getting sensor data for box: {}, sensors: {}", boxNo, sensorIds);
            return fboxService.getSensorData(boxNo, sensorIds);
        } catch (Exception e) {
            logger.error("Failed to get sensor data: {}", e.getMessage(), e);
            throw new RuntimeException("Failed to get sensor data: " + e.getMessage());
        }
    }

    @ApiOperation("获取传感器历史数据")
    @GetMapping("/history")
    public List<SensorDataDTO> getHistoryData(
        @RequestParam String deviceId,
        @RequestParam(defaultValue = "24") Integer hours
    ) {
        // 计算24小时前的时间
        Date startTime = new Date(System.currentTimeMillis() - hours * 3600 * 1000L);
        List<SensorData> historyData = sensorDataDao.findHistoryData(deviceId, startTime);
        
        // 转换为DTO
        return historyData.stream()
            .map(data -> {
                SensorDataDTO dto = new SensorDataDTO();
                dto.setId(data.getDevice().getDeviceSerial());
                dto.setName(data.getName());
                dto.setValue(data.getValue());
                return dto;
            })
            .collect(Collectors.toList());
    }
} 